package com.mq.client;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;

import java.util.Random;

/**
 * 消息持久化
 *
 * @author xwj
 * @date 2019/2/28
 */
public class PersistenceTask {
    private final static String QUEUE_NAME = "task_queue";

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        // 开启持久化
        boolean durable = true;
        channel.queueDeclare(QUEUE_NAME, durable, false, false, null);
        String msg = getMessage();
        // 持久化配置
        channel.basicPublish("", QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, msg.getBytes());
        System.out.println("Send task:" + msg);
    }

    private static String getMessage() {
        Random random = new Random();
        int taskTime = random.nextInt(5) + 1;
        StringBuilder msg = new StringBuilder();
        for (int i = 0; i < taskTime; i++) {
            msg.append(".");
        }
        return msg.toString();
    }
}
